package com.jt.shop.controller;

import com.jt.shop.model.Address;
import com.jt.shop.service.AddressService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by he on 2015/9/5.
 */
@RequestMapping("/address")
@Controller
public class AddressController {

    @Resource
    private AddressService addressService;

    @RequestMapping("/add")
    public String add() {
        return "address/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(@Valid Address address, int userId, BindingResult br, Model model) {
        if (br.hasErrors()) {
            return "address/add";
        }
        int count = addressService.add(address, userId);
        if (count > 0) {
            model.addAttribute("result", "添加地址成功");
        }
        return "address/add";
    }

    @RequestMapping("/list")
    public String list(int userId, Model model) {
        List<Address> addressList = addressService.listByUserId(userId);
        model.addAttribute("addressList", addressList);
        return "address/list";
    }

    @RequestMapping("/delete")
    public String delete(int id, int userId) {
        addressService.delete(id);
        return "redirect:/address/list?userId="+userId;
    }

    @RequestMapping("/update")
    public String update(int id, Model model) {
        Address address = addressService.find(id);
        model.addAttribute("address", address);
        return "address/update";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@Valid Address address, int userId, BindingResult br) {
        if (br.hasErrors()) {
            return "address/update";
        }
        addressService.update(address);
        return "redirect:/address/list?userId="+userId;
    }

}
